#import "SpeedometerView.h"
#import "ExtraCategories.h"
#import "MyDocument.h"

@implementation SpeedometerView

+ (id)defaultAnimationForKey:(NSString *)key {
	
    if ([key isEqualToString:@"speed"] || [key isEqualToString:@"curvature"] || [key isEqualToString:@"ticks"]) {
        return [CABasicAnimation animation];
    } else {
        return [super defaultAnimationForKey:key];
    }
}
- (void) awakeFromNib
{
	mouseScrollX = 0.0;
	mouseScrollY = 0.0;
	[ self setupRenderTimer ];
}
- (void) setupRenderTimer
{
	NSTimeInterval timeInterval = 1.0/60.0;
	
	myDrawTimer = [ [ NSTimer scheduledTimerWithTimeInterval:timeInterval
													  target:self
													selector:@selector( drawMe: )
													userInfo:nil repeats:YES ] retain ];
	[ [ NSRunLoop currentRunLoop ] addTimer:myDrawTimer
									forMode:NSEventTrackingRunLoopMode ];
	[ [ NSRunLoop currentRunLoop ] addTimer:myDrawTimer
									forMode:NSModalPanelRunLoopMode ];
}
- (void) drawMe:(NSTimer *)timer;
{
	[self display];
	//[self setNeedsDisplay:YES];
}
- (id)initWithFrame:(NSRect)frameRect {
	if ((self = [super initWithFrame:frameRect]) != nil) {
		[self setSpeed: 10.0];
		[self setCurvature: 10.0];
		[self setTicks: 0];
		done = 0;
	}
	return self;
}

float	Pin( float min, float max, float value ) {
	if (value < min)		return(min);
	else if (value > max)	return(max);
	else					return(value);
}

- (float)speed {
    return speed;
}

- (void)setSpeed:(float)value {
	float nextSpeed	= Pin( 0, 100, value);
	
    if (speed != nextSpeed) {
        speed = nextSpeed;
		[self setNeedsDisplay:YES];
    }
}

- (float)curvature {
    return curvature;
}

- (void)setCurvature:(float)value {
	float nextCurvature	= Pin( 0, 100, value);
	
	if (curvature != nextCurvature) {
        curvature = nextCurvature;
		[self setNeedsDisplay:YES];
    }
	
}

- (int)ticks {
    return ticks;
}


- (void)setTicks:(float)value {
	int nextTicks	= (int) Pin( 0, 20, value);
	
    if (ticks != nextTicks) {
        ticks = nextTicks;
		[self setNeedsDisplay:YES];
    }
}


- (NSBezierPath*) speedPointerPath {
	NSBezierPath* speedPointer = [NSBezierPath bezierPath];
	[speedPointer moveToPoint:NSMakePoint(134.39, 218.05)];
	[speedPointer curveToPoint:NSMakePoint(137.95, 219.75)
				 controlPoint1:NSMakePoint(134.39, 218.05)
				 controlPoint2:NSMakePoint(137.95, 219.75)];
	[speedPointer curveToPoint:NSMakePoint(141.78, 357.55)
				 controlPoint1:NSMakePoint(137.95, 219.75)
				 controlPoint2:NSMakePoint(141.78, 357.55)];
	[speedPointer curveToPoint:NSMakePoint(151.13, 356.31)
				 controlPoint1:NSMakePoint(141.78, 357.55)
				 controlPoint2:NSMakePoint(145.39, 359.54)];
	[speedPointer curveToPoint:NSMakePoint(158.95, 349.86)
				 controlPoint1:NSMakePoint(156.87, 353.08)
				 controlPoint2:NSMakePoint(158.95, 349.86)];
	[speedPointer curveToPoint:NSMakePoint(134.49, 415.99)
				 controlPoint1:NSMakePoint(158.95, 349.86)
				 controlPoint2:NSMakePoint(134.49, 415.99)];
	[speedPointer curveToPoint:NSMakePoint(110.02, 349.86)
				 controlPoint1:NSMakePoint(134.49, 415.99)
				 controlPoint2:NSMakePoint(110.02, 349.86)];
	[speedPointer curveToPoint:NSMakePoint(117.84, 356.31)
				 controlPoint1:NSMakePoint(110.02, 349.86)
				 controlPoint2:NSMakePoint(112.1, 353.08)];
	[speedPointer curveToPoint:NSMakePoint(127.19, 357.55)
				 controlPoint1:NSMakePoint(123.58, 359.54)
				 controlPoint2:NSMakePoint(127.19, 357.55)];
	[speedPointer curveToPoint:NSMakePoint(131.02, 219.75)
				 controlPoint1:NSMakePoint(127.19, 357.55)
				 controlPoint2:NSMakePoint(131.02, 219.75)];
	[speedPointer curveToPoint:NSMakePoint(134.39, 218.05)
				 controlPoint1:NSMakePoint(131.02, 219.75)
				 controlPoint2:NSMakePoint(134.39, 218.05)];
	[speedPointer closePath];
	[speedPointer setLineJoinStyle:NSRoundLineJoinStyle];
	[speedPointer setLineCapStyle:NSRoundLineCapStyle];
	[speedPointer setLineWidth: 0.25];
	return speedPointer;
}

- (NSBezierPath*) ornamentPath {
	NSBezierPath* ornament = [NSBezierPath bezierPath];
	[ornament moveToPoint:NSMakePoint(251.77, 135.25)];
	[ornament curveToPoint:NSMakePoint(260.31, 146.12)
			 controlPoint1:NSMakePoint(252.88, 144.62)
			 controlPoint2:NSMakePoint(260.31, 146.12)];
	[ornament curveToPoint:NSMakePoint(266.06, 343.75)
			 controlPoint1:NSMakePoint(260.31, 146.12)
			 controlPoint2:NSMakePoint(266.06, 343.75)];
	[ornament curveToPoint:NSMakePoint(251.79, 355.06)
			 controlPoint1:NSMakePoint(266.06, 343.75)
			 controlPoint2:NSMakePoint(257.38, 346.25)];
	[ornament curveToPoint:NSMakePoint(237.52, 343.75)
			 controlPoint1:NSMakePoint(245.5, 345.88)
			 controlPoint2:NSMakePoint(237.52, 343.75)];
	[ornament curveToPoint:NSMakePoint(243.27, 146.12)
			 controlPoint1:NSMakePoint(237.52, 343.75)
			 controlPoint2:NSMakePoint(243.27, 146.12)];
	[ornament curveToPoint:NSMakePoint(251.77, 135.25)
			 controlPoint1:NSMakePoint(243.27, 146.12)
			 controlPoint2:NSMakePoint(250.25, 144.75)];
	[ornament closePath];
	[ornament setLineJoinStyle:NSRoundLineJoinStyle];
	[ornament setLineCapStyle:NSRoundLineCapStyle];
	[ornament setLineWidth: 0.25];
	return ornament;
}

- (NSBezierPath*) tickMarkPath {
	NSBezierPath* tickMark = [NSBezierPath bezierPath];
	[tickMark moveToPoint:NSMakePoint(225.81, 358.28)];
	[tickMark curveToPoint:NSMakePoint(222.7, 385.11)
			 controlPoint1:NSMakePoint(225.81, 358.28)
			 controlPoint2:NSMakePoint(222.7, 385.11)];
	[tickMark curveToPoint:NSMakePoint(235.97, 385.11)
			 controlPoint1:NSMakePoint(222.7, 385.11)
			 controlPoint2:NSMakePoint(235.97, 385.11)];
	[tickMark curveToPoint:NSMakePoint(232.86, 358.28)
			 controlPoint1:NSMakePoint(235.97, 385.11)
			 controlPoint2:NSMakePoint(232.86, 358.28)];
	[tickMark curveToPoint:NSMakePoint(225.81, 358.28)
			 controlPoint1:NSMakePoint(232.86, 358.28)
			 controlPoint2:NSMakePoint(225.81, 358.28)];
	[tickMark closePath];
	[tickMark setLineJoinStyle:NSRoundLineJoinStyle];
	[tickMark setLineCapStyle:NSRoundLineCapStyle];
	[tickMark setLineWidth: 0.25];
	return tickMark;
}

- (void)drawRect:(NSRect)rect {
	
	[myGLView setFly:curvature];
	
	id myDNAobjects;
	int myNum;
	id newMan= [[NSMutableArray alloc] init];
	
	myDNAobjects = [DNAController arrangedObjects];
	int i;
	float jax = 0;
	
	for (i=0; i < [myDNAobjects count]; i++)
	{
		int j = [[[myDNAobjects objectAtIndex:i ] valueForKey:@"sequence"] length];
		if (j>jax)
			jax = j;
	}
	//	NSLog(@"jax = %f",jax);
	if ([myDNAobjects count] > 20)
		myNum = 20;
	else
		myNum = [myDNAobjects count];
	
	if ([self ticks] != myNum)
	{
		//NSLog(@"Doing it!");
		[self setTicks:myNum];
		[myDocument applySpeedometerSettings:self];
	}
	
	
	///		[[[NSDocumentController sharedDocumentController] currentDocument] doIT:newMan];
	
	
	NSPoint pt;
    pt = [[NSApp mainWindow] mouseLocationOutsideOfEventStream];
	
	pt = [self convertPoint:pt fromView:nil];
	//pt.x -= mouseScrollX;
	//pt.y += mouseScrollY -2;
	
	NSRect boundary = [self bounds];
	
	const float shadowAngle = -35.0;
	NSPoint center;
	
	center.x = boundary.origin.x + (boundary.size.width/2.0);
	center.y = boundary.origin.y + (boundary.size.height/2.0);
	
	float dnaShadow = 5.0;
	float topLineOffsetx = 10.0;
	float topLineOffsety = 20.0;
	float seqSizeX = boundary.size.width - topLineOffsetx;
	float seqSizeY = boundary.size.height/2.0;
	
	// START CODON ARROW
	
	
	id transform = [NSAffineTransform transform];
	id identity = [NSAffineTransform transform];
	for (i=0; i < [self ticks]; i++)
	{
		id transform = [NSAffineTransform transform];
		
		//		NSBezierPath* ornament = [self ornamentPath];
		
		//		[transform translateXBy:0 yBy:center.y - topLineOffsety -i*30 ];
		//	[transform concat];
		/*		[ornament transformUsingAffineTransform: 
		 [transform
		 scaleBounds: [ornament bounds]
		 toHeight: 50
		 centeredAboveOrigin: 0]];	*/
		/*		NSGradient *ornamentGradient = [[NSGradient alloc]
		 initWithStartingColor: [NSColor greenColor]
		 endingColor: [NSColor whiteColor]];
		 [ornamentGradient drawInBezierPath:ornament angle:90];
		 [ornamentGradient release];
		 [[NSColor greenColor] set];
		 [ornament stroke];*/
		//	id theCluster = [[[[NCUController selectedObjects] objectAtIndex:0] mutableSetValueForKey:@"cluster"] anyObject];		
		//[transform initWithTransform:identity];
		id myObject = [[DNAController arrangedObjects] objectAtIndex:i ];
		int myLength = [[myObject valueForKey:@"sequence"] length];
		NSString * myName = [myObject valueForKey:@"title"];
		NSString * mySequence =  [myObject valueForKey:@"sequence"];
		//		int myLength = 10;//[[[myDNAobjects objectAtIndex:i] valueForKey:@"sequence"] length];
		
		
		int value = boundary.size.height-topLineOffsety-i*30;
		
		NSBezierPath* dnaSequenceRect = [[[NSBezierPath alloc] init] autorelease];
		
		[dnaSequenceRect appendBezierPathWithRoundedRect:
		 //		 NSMakeRect(topLineOffsetx+mouseScrollX, value - [self speed]/2.0 + mouseScrollY , seqSizeX-topLineOffsetx, 4 + [self speed]) xRadius:2.5 yRadius:2.5];
		 NSMakeRect(topLineOffsetx+mouseScrollX, value - [self speed]/2.0 + mouseScrollY , myLength/jax*seqSizeX-topLineOffsetx, 4 + [self speed]) xRadius:2.5 yRadius:2.5];
		[dnaSequenceRect closePath];
		
		//		[transform scaleBounds:[dnaSequenceRect bounds] toHeight:[dnaSequenceRect bounds].size.height+[self curvature] centeredAboveOrigin:center.x+10];
		//		[transform translateXBy:200+mouseScrollX yBy:mouseScrollY/2];
		//		[transform concat];	
		
		[dnaSequenceRect setLineJoinStyle:NSRoundLineJoinStyle];
		
		
		//NSLog(@"%f, %f",pt.x, pt.y);
		
		if ([dnaSequenceRect containsPoint:pt])
		{
			//[NCUTextView setSelectedRange:NSMakeRange(0,NCULength)];
			[dnaSequenceRect setLineWidth: 1.5];
		}
		else
			[dnaSequenceRect setLineWidth: 0.5];
		
		NSColor *newBackgroundColor = [NSColor colorWithCalibratedRed:.45 green:.43 blue:8.0 alpha: 1.0];
		NSGradient *newBackgroundGradient = [[NSGradient alloc]
											 initWithColorsAndLocations:
											 [NSColor whiteColor], 0.0, [NSColor whiteColor], 0.3, 
											 newBackgroundColor, 0.7, newBackgroundColor, 1.0,  
											 nil];
		
		
		[dnaSequenceRect fillWithShadowAtDegrees:shadowAngle withDistance: dnaShadow];
		
		NSPoint newGradientCenter = 
		[[[NSAffineTransform transform]
		  mapFrom:[dnaSequenceRect bounds] to: NSMakeRect(-1.0,-1.0,2.0,2.0)] transformPoint: center];
		[newBackgroundGradient drawInBezierPath: dnaSequenceRect relativeCenterPosition: newGradientCenter];
		[[NSColor blackColor] set];
		[dnaSequenceRect stroke];
		//[transform invert];
		//[transform concat];
		//					   topLineOffsetx+mouseScrollX, value - [self speed]/2.0 + mouseScrollY 
		[transform translateXBy:topLineOffsetx+mouseScrollX - 100 yBy:value+5 - [self speed]/2.0 + mouseScrollY];
		[transform concat];
		
		//[line substringWithRange:NSMakeRange(10, 70)]
		
		NSFont* labelFont = [[NSFont labelFontOfSize:[self curvature]] printerFont];
		
		
		//([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
		int max=1;
		//		max = ([myName length] > 1 ) ? 10 :  1;
		if ([myName length] >25)
		{
			myName = [myName substringWithRange:NSMakeRange(1, 25)]; 
		}
		if ([mySequence length] > 30)
		{
			mySequence = [mySequence substringWithRange:NSMakeRange(1, 30)];
		}
		NSBezierPath* nthLabelPath = [myName  bezierWithFont: labelFont];
		//		[transform translateXBy:100 yBy:100];
		[nthLabelPath transformUsingAffineTransform: 
		 [[NSAffineTransform transform]
		  scaleBounds: [nthLabelPath bounds] toHeight: [nthLabelPath bounds].size.height
		  centeredAboveOrigin:[labelFont descender]]];
		//[transform translateXBy:100 yBy:200];
		[nthLabelPath transformUsingAffineTransform: [NSAffineTransform transform]]; 
		//					   [nthLabelPath fillWithShadowAtDegrees:shadowAngle withDistance: 10];
		[[NSColor blackColor] set];
		[nthLabelPath fill];
		[nthLabelPath stroke];
		[transform invert];
		[transform concat];
		
		NSPoint drawSpot;
		drawSpot.x = topLineOffsetx+mouseScrollX+2;
		drawSpot.y = value - [self speed]/2.0 + mouseScrollY;
		[mySequence drawAtPoint:drawSpot withAttributes:nil];
	}
	
	
	/*for (i=0; i < [self ticks]; i++)
	 {
	 id transform = [NSAffineTransform transform];
	 
	 [transform translateXBy:center.x+mouseScrollX yBy:boundary.size.height-topLineOffsety-i*30+mouseScrollY];
	 [transform concat];
	 
	 NSFont* labelFont = [[NSFont labelFontOfSize:[self curvature]] printerFont];
	 NSString *theLabel = @"GGTCGAGGTTCATTTGAAATTATTACCTGACCCACAAAGACGGGCATCGATTTCAGCCATCATTGTTTACATCCCATAGTATGTAGGATGCGAAAACTCCAATGGTCAAGTCACGATAGGCAGTGATTGGCTGTCGCTGACG";
	 NSBezierPath* nthLabelPath = [theLabel bezierWithFont: labelFont];
	 //		[transform translateXBy:100 yBy:100];
	 [nthLabelPath transformUsingAffineTransform: 
	 [[NSAffineTransform transform]
	 scaleBounds: [nthLabelPath bounds] toHeight: [nthLabelPath bounds].size.height
	 centeredAboveOrigin:[labelFont descender]]];
	 //[transform translateXBy:100 yBy:200];
	 [nthLabelPath transformUsingAffineTransform: [NSAffineTransform transform]]; 
	 [nthLabelPath fillWithShadowAtDegrees:shadowAngle withDistance: 10];
	 [[NSColor blackColor] set];
	 [nthLabelPath stroke];
	 [transform invert];
	 [transform concat];
	 
	 //		[transform translateXBy:-100 yBy:-(100-i*10-30*(speed/100)) ];
	 
	 ///***********************************************************
	 }
	 */
	
	
	/*
	 id myDocController = [NSDocumentController sharedDocumentController];
	 id highlightDocument = [myDocController currentDocument];
	 
	 
	 NSPoint pt;
	 pt = [[NSApp mainWindow] mouseLocationOutsideOfEventStream];
	 
	 pt = [self convertPoint:pt fromView:nil];
	 pt.x -= mouseScrollX;
	 pt.y -= mouseScrollY -2;
	 
	 id dnaObjects = [DNAController arrangedObjects];
	 NSRect boundary = [self bounds];
	 NSPoint center;
	 
	 center.x = boundary.origin.x + (boundary.size.width/2.0);
	 center.y = boundary.origin.y + (boundary.size.height/2.0);
	 id transform = [NSAffineTransform transform];
	 id identity = [NSAffineTransform transform];
	 
	 [transform initWithTransform:identity];
	 [transform translateXBy:10 yBy:-center.y];
	 [transform concat];	
	 
	 NSBezierPath* ornament = [self ornamentPath];
	 
	 
	 [transform translateXBy:10+mouseScrollX yBy:center.y+mouseScrollY];
	 [transform concat];
	 
	 [ornament transformUsingAffineTransform: 
	 [transform
	 scaleBounds: [ornament bounds]
	 toHeight: 25
	 centeredAboveOrigin: 0]];	
	 NSGradient *ornamentGradient = [[NSGradient alloc]
	 initWithStartingColor: [NSColor greenColor]
	 endingColor: [NSColor whiteColor]];
	 [ornamentGradient drawInBezierPath:ornament angle:90];
	 [ornamentGradient release];
	 [[NSColor greenColor] set];
	 [ornament stroke];
	 
	 
	 NSBezierPath* dnaSequenceRect = [[[NSBezierPath alloc] init] autorelease];
	 
	 [dnaSequenceRect appendBezierPathWithRoundedRect:
	 NSMakeRect(10, 10, 200, 300) xRadius:2.5 yRadius:2.5];
	 [dnaSequenceRect closePath];
	 if (zoom < 1)
	 zoom =1;
	 [dnaSequenceRect transformUsingAffineTransform:[transform scaleBounds:[dnaSequenceRect bounds] toHeight:zoom/2 centeredAboveOrigin:0]];
	 
	 [dnaSequenceRect setLineJoinStyle:NSRoundLineJoinStyle];
	 if ([dnaSequenceRect containsPoint:pt])
	 {
	 //[DNATextView setSelectedRange:NSMakeRange(0,NCULength)];
	 [dnaSequenceRect setLineWidth: 1.5];
	 }
	 else
	 [dnaSequenceRect setLineWidth: 0.5];
	 
	 NSColor *newBackgroundColor = [NSColor colorWithCalibratedRed:.45 green:.43 blue:8.0 alpha: 1.0];
	 NSGradient *newBackgroundGradient = [[NSGradient alloc]
	 initWithColorsAndLocations:
	 [NSColor whiteColor], 0.0, [NSColor whiteColor], 0.3, 
	 newBackgroundColor, 0.7, newBackgroundColor, 1.0,  
	 nil];
	 
	 
	 [dnaSequenceRect fillWithShadowAtDegrees:45 withDistance: 5];
	 
	 NSPoint newGradientCenter = 
	 [[[NSAffineTransform transform]
	 mapFrom:[dnaSequenceRect bounds] to: NSMakeRect(-1.0,-1.0,2.0,2.0)] transformPoint: center];
	 [newBackgroundGradient drawInBezierPath: dnaSequenceRect relativeCenterPosition: newGradientCenter];
	 [[NSColor blackColor] set];
	 [dnaSequenceRect stroke];
	 */
	
}



- (BOOL)mouseDownCanMoveWindow {
	
	return NO;	
	
}

- (void)scrollWheel:(NSEvent *)theEvent
{
	
	mouseScrollX -= [theEvent deltaX];
	mouseScrollY += [theEvent deltaY];
	//	NSLog(@"your point %f,%f",mouseScrollX, mouseScrollY);	
}

- (void)mouseEntered:(NSEvent *)theEvent
{
	NSPoint local_point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
	//NSLog(@"your point %f,%f",local_point.x,local_point.y);
	
}
- (void)mouseDragged:(NSEvent *)theEvent {
	//NSPoint local_point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
	
}



@end





